﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using DungChung;
namespace CoVuaServer
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString;
            string myIP = GetMyIPAddress();
            Console.WriteLine("Dia chi ip la: " + myIP);

            Console.WriteLine("Nhap thong tin database:");
            Console.Write("Nhap server name:");
            string serverName = Console.ReadLine();
            Console.Write("Nhap database: ");
            string database = Console.ReadLine();
            connectionString = string.Format("server = {0};database= {1}; Integrated security = true", serverName, database);
            TcpListener listener = new TcpListener(IPAddress.Parse(myIP), 8000);
            listener.Start();
            bool isContinous = true;
            DangNhapProcess dangNhap = new DangNhapProcess(connectionString);
            DangKiProcess dangKi = new DangKiProcess(connectionString);
            Console.WriteLine("Server da khoi dong xong! Client co the ket noi!");
            while (isContinous)
            {
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                BinaryReader reader = new BinaryReader(stream);
                BinaryWriter writer = new BinaryWriter(stream);
                string nhanDang = reader.ReadString();
                if (nhanDang == MyTask.DangKi)
                {
                    Console.WriteLine("Co nguoi yeu cau dang ki");
                    Thread thread = new Thread(new ParameterizedThreadStart(dangKi.Start));
                    thread.IsBackground = true;
                    thread.Start(client);
                }
                if (nhanDang == MyTask.DangNhap)
                {
                    Console.WriteLine("Co nguoi yeu cau dang nhap");
                    Thread thread = new Thread(new ParameterizedThreadStart(dangNhap.Start));
                    thread.IsBackground = true;
                    thread.Start(client);
                }
                if (nhanDang == "KiemTra")
                {
                    writer.Write("OK");
                    Console.WriteLine("Co nguoi truy cap server");
                }
            }
        }

        public static string GetMyIPAddress()
        {
            IPHostEntry host;
            string localIP = "?";
            
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

    }

    
   
}
